package com.example.service.appointment;

import cn.hutool.core.util.ObjectUtil;
import com.example.common.enums.ResultCodeEnum;
import com.example.common.enums.RoleEnum;
import com.example.exception.CustomException;
import com.example.mapper.appointment.PlanMapper;
import com.example.mapper.medical.DoctorMapper;
import com.example.model.entity.appointment.MedicalCard;
import com.example.model.entity.appointment.Plan;
import com.example.model.entity.other.Account;
import com.example.model.vo.PlanVO;
import com.example.utils.TokenUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import java.util.List;

/**
 * 医生排班表业务处理
 **/
@Service
public class PlanService {

    @Resource
    private PlanMapper planMapper;
    @Resource
    private DoctorMapper doctorMapper;
    /**
     * 新增
     */
    public void add(Plan plan) {
        Plan dbPlan = planMapper.selectByTime(plan.getDoctorID(),plan.getWeek(), plan.getTime());
        if (ObjectUtil.isNotNull(dbPlan)) {
            throw new CustomException(ResultCodeEnum.PLAN_DOCTOR_EXIST);
        }
        planMapper.insert(plan);
    }

    /**
     * 删除
     */
    public void deleteById(Integer id) {
        planMapper.deleteById(id);
    }

    /**
     * 批量删除
     */
    public void deleteBatch(List<Integer> ids) {
        for (Integer id : ids) {
            planMapper.deleteById(id);
        }
    }

    /**
     * 修改
     */
    public void updateById(Plan plan) {
        Plan dbPlan = planMapper.selectByTime(plan.getDoctorID(),plan.getWeek(), plan.getTime());
        if (ObjectUtil.isNotNull(dbPlan)) {
            throw new CustomException(ResultCodeEnum.PLAN_DOCTOR_EXIST);
        }
        planMapper.updateById(plan);
    }

    /**
     * 根据ID查询
     */
    public Plan selectById(Integer id) {
        return planMapper.selectById(id);
    }

    /**
     * 查询所有
     */
    public List<PlanVO> selectAll(Plan plan) {
        Account currentUser = TokenUtils.getCurrentUser();
        if(RoleEnum.HOSPITAL.name().equals(currentUser.getRole())){
            plan.setHospitalId(currentUser.getId());
        }else if(RoleEnum.DOCTOR.name().equals(currentUser.getRole())){
            plan.setDoctorID(currentUser.getId());
        }
        return planMapper.selectAll(plan);
    }

    /**
     * 分页查询
     */
    public PageInfo<PlanVO> selectPage(Plan plan, Integer pageNum, Integer pageSize) {
        Account currentUser = TokenUtils.getCurrentUser();
        if(RoleEnum.HOSPITAL.name().equals(currentUser.getRole())){
            plan.setHospitalId(currentUser.getId());
        }else if(RoleEnum.DOCTOR.name().equals(currentUser.getRole())){
            plan.setDoctorID(currentUser.getId());
        }
        PageHelper.startPage(pageNum, pageSize);
        List<PlanVO> list = planMapper.selectAll(plan);
        return PageInfo.of(list);
    }

}
